<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="门店" prop="itemType">
        <el-tree-select
            v-model="queryParams.deptId"
            :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择门店"
            check-strictly
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable style="width: 200px">
          <el-option
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户电话" prop="customerPhone">
        <el-input
            v-model="queryParams.customerPhone"
            placeholder="请输入客户电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户地址" prop="customerAddress">
        <el-input
            v-model="queryParams.customerAddress"
            placeholder="请输入客户地址"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单日期" style="width: 308px">
        <el-date-picker
            v-model="daterangeOrderDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="出货日期" style="width: 308px">
        <el-date-picker
            v-model="daterangeShipmentDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:order:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:order:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['system:order:remove']"
              >删除</el-button>
            </el-col>-->

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="门店" align="center" prop="dept.deptName" width="100"/>
      <el-table-column label="订单编号" align="center" prop="orderNo" width="150"/>
      <el-table-column label="销售员" align="center" prop="createBy"/>
      <el-table-column label="客户姓名" align="center" prop="customerName"/>
      <el-table-column label="客户电话" align="center" prop="customerPhone"/>
      <el-table-column label="客户地址" align="center" prop="customerAddress" show-overflow-tooltip/>
      <el-table-column label="货运方式" align="center" prop="freightType"/>
      <el-table-column label="结款方式" align="center" prop="payType"/>
      <el-table-column label="总价" align="center" prop="totalPrice"/>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出货日期" align="center" prop="shipmentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shipmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="70">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:order:edit']">修改
          </el-button>
          <!--
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:order:remove']">删除</el-button>
          -->
          <el-button link type="warning" icon="Download" @click="handleExport(scope.row)"
                     v-hasPermi="['system:order:export']">导出
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body :close-on-press-escape="false" :close-on-click-modal="false">
      <el-form ref="orderRef" inline :model="form" :rules="rules" label-width="150px" label-position="top">
        <el-form-item label="所属门店" prop="deptId">
          <el-tree-select
              v-model="form.deptId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              check-strictly
              disabled
          />
        </el-form-item>

        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="" disabled/>
        </el-form-item>

        <el-form-item label="订单金额" prop="totalPrice">
          <el-input-number v-model="form.totalPrice" placeholder="" disabled/>
        </el-form-item>

        <el-form-item label="成交价" prop="transactionPrice">
          <el-input-number v-model="form.transactionPrice" :min="0" placeholder="" :change="changeTransactionPrice()"/>
        </el-form-item>

        <el-form-item label="定金" prop="actuallyPaid">
          <el-input-number v-model="form.actuallyPaid" :min="0" placeholder="" :change="changeActuallyPaid()"/>
        </el-form-item>
        <el-form-item label="尾款" prop="actuallyPaid">
          <el-input-number v-model="form.finalPayment"  placeholder="" disabled/>
        </el-form-item>

        <el-form-item label="订单日期" prop="orderDate">
          <el-date-picker clearable
                          disabled
                          v-model="form.orderDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择订单日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出货日期" prop="shipmentDate">
          <el-date-picker clearable
                          v-model="form.shipmentDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择出货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="订单状态" clearable>
            <el-option
                v-for="dict in order_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入订单备注" style="width: 240px" autosize/>
        </el-form-item>

        <el-divider content-position="center">客户信息</el-divider>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户姓名"/>
        </el-form-item>
        <el-form-item label="客户电话" prop="customerPhone">
          <el-input v-model="form.customerPhone" placeholder="请输入客户电话"/>
        </el-form-item>
        <el-form-item label="客户地址" prop="customerAddress">
          <el-input v-model="form.customerAddress" placeholder="请输入客户地址"/>
        </el-form-item>

        <el-divider content-position="center">订单详情信息</el-divider>
        <el-row :gutter="10" class="mb8" v-if="isUpdate">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSellOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSellOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="sellOrderDetailList" border :row-class-name="rowSellOrderDetailIndex"
                  @selection-change="handleSellOrderDetailSelectionChange" ref="sellOrderDetail">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="主图" align="center" prop="imgUrl" width="100">
            <template #default="scope">
              <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="型号" prop="itemModel" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.itemModel" disabled placeholder=""/>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="itemName" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.itemName" disabled placeholder=""/>
            </template>
          </el-table-column>
          <el-table-column label="分类" prop="itemType" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.itemType" disabled placeholder="请选择分类">
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.unit" disabled placeholder=""/>
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="specification" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.specification" placeholder="请输入规格"/>
            </template>
          </el-table-column>

          <el-table-column label="区域" prop="area" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.area" placeholder=""/>
            </template>
          </el-table-column>

          <el-table-column label="材质" prop="texture" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.texture" placeholder=""/>
            </template>
          </el-table-column>

          <el-table-column label="颜色" prop="color" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.color" placeholder=""/>
            </template>
          </el-table-column>

          <el-table-column label="数量" fixed="right" prop="quantity" width="175">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" placeholder=""
                               :change="changeTotalPrice(scope.row)"/>
            </template>
          </el-table-column>

          <el-table-column label="零售价" fixed="right" prop="retailPrice" width="175">
            <template #default="scope">
              <el-input-number v-model="scope.row.retailPrice" :min="0" placeholder="" precision="2"
                               controls-position="right" :change="changeTotalPrice(scope.row)"/>
            </template>
          </el-table-column>

          <el-table-column label="出厂价" fixed="right" prop="purchasePrice" width="125"  v-hasRole="['admin', 'dealer','system']">
            <template #default="scope">
              <el-input v-model="scope.row.purchasePrice" disabled />
            </template>
          </el-table-column>

          <el-table-column label="总价" fixed="right" prop="totalPrice" width="175">
            <template #default="scope">
              <el-input-number v-model="scope.row.totalPrice" width="100" :min="0" precision="2"
                               controls-position="right" placeholder="" disabled/>
            </template>
          </el-table-column>

          <el-table-column label="备注" fixed="right" prop="remark" width="175">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="isUpdate">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 选择产品信息 -->
    <el-dialog title="产品信息" v-model="itemOpen" width="1200px" append-to-body :close-on-press-escape="false" :close-on-click-modal="false">
      <itemComponent ref="items"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="itemSubmitForm">确 定</el-button>
          <el-button @click="itemCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup name="Order">
import {listOrder, getOrder, delOrder, addOrder, updateOrder} from "@/api/system/order";
import {deptTreeSelect} from "@/api/system/user";
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

import itemComponent from '../item/itemComponent.vue';
import useUserStore from '@/store/modules/user'
import {markRaw, onMounted} from "vue";
import * as echarts from "echarts";

const userStore = useUserStore()
const {proxy} = getCurrentInstance();
const {order_status} = proxy.useDict("order_status");

const deptOptions = ref(undefined);
const items = ref(null);
const orderList = ref([]);
const sellOrderDetailList = ref([]);
const open = ref(false);
const itemOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const isUpdate = ref([]);
const checkedSellOrderDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeOrderDate = ref([]);
const daterangeShipmentDate = ref([]);

const userInfo = computed(() => userStore.userInfo)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    customerName: null,
    customerPhone: null,
    customerAddress: null,
    freightType: null,
    payType: null,
    orderDate: null,
    shipmentDate: null,
    status: null,
  },
  rules: {
    customerName: [
      {required: true, message: "客户名称不能为空", trigger: "blur"}
    ],
    customerPhone: [
      {required: true, message: "客户电话不能为空", trigger: "blur"},
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    customerAddress: [
      {required: true, message: "客户地址不能为空", trigger: "blur"}
    ],
    transactionPrice:[
      {required: true, message: "请输入成交价！", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询订单信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeOrderDate && '' != daterangeOrderDate) {
    queryParams.value.params["beginOrderDate"] = daterangeOrderDate.value[0];
    queryParams.value.params["endOrderDate"] = daterangeOrderDate.value[1];
  }
  if (null != daterangeShipmentDate && '' != daterangeShipmentDate) {
    queryParams.value.params["beginShipmentDate"] = daterangeShipmentDate.value[0];
    queryParams.value.params["endShipmentDate"] = daterangeShipmentDate.value[1];
  }
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    sellOrderId: null,
    orderNo: null,
    customerName: null,
    customerPhone: null,
    customerAddress: null,
    freightType: null,
    payType: null,
    orderDate: null,
    shipmentDate: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deptName: null,
    deptId: null,
    totalPrice: 0,
    actuallyPaid: 0,
    finalPayment: 0,
    transactionPrice:null
  };
  sellOrderDetailList.value = [];
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeOrderDate.value = [];
  daterangeShipmentDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sellOrderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 关闭产品信息
function itemCancel() {
  items.value.getList()
  itemOpen.value = false
}

//提交选中的产品信息
function itemSubmitForm() {
  //添加选中的数据
  items.value.ids.forEach((item) => {
    item.quantity = 1
    sellOrderDetailList.value.push(item);
  })
  itemOpen.value = false
  items.value.getList()
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.deptId = userInfo.value.dept.deptId
  form.value.deptName = userInfo.value.dept.deptName
  open.value = true;
  title.value = "添加订单信息";
  isUpdate.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _sellOrderId = row.sellOrderId || ids.value
  getOrder(_sellOrderId).then(response => {
    form.value = response.data;
    sellOrderDetailList.value = response.data.sellOrderDetailList;
    open.value = true;
    title.value = "修改订单信息";
    isUpdate.value = form.value.status === '0' || !form.value.status
  });
}

/** 提交按钮 */
function submitForm() {
  //校验售价与数量是否填写
  for (let item of sellOrderDetailList.value) {
    if (!item.retailPrice || !item.quantity) {
      proxy.$modal.msgError("请填写售价与数量!");
      return
    }
  }
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      form.value.sellOrderDetailList = sellOrderDetailList.value;
      if (form.value.sellOrderId != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _sellOrderIds = row.sellOrderId || ids.value;
  proxy.$modal.confirm('是否确认删除订单信息编号为"' + _sellOrderIds + '"的数据项？').then(function () {
    return delOrder(_sellOrderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 订单详情序号 */
function rowSellOrderDetailIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 订单详情添加按钮操作 */
function handleAddSellOrderDetail() {
  itemOpen.value = true
}


/** 订单详情删除按钮操作 */
function handleDeleteSellOrderDetail() {
  if (checkedSellOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的订单详情数据");
  } else {
    const sellOrderDetails = sellOrderDetailList.value;
    const checkedSellOrderDetails = checkedSellOrderDetail.value;
    sellOrderDetailList.value = sellOrderDetails.filter(function (item) {
      return checkedSellOrderDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleSellOrderDetailSelectionChange(selection) {
  checkedSellOrderDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport(row) {
  let b = checkRole(['dealer']);
  let params = {"isDealer":b};
  row.dept = null
  proxy.download('system/order/exportOrderInfo', {...row,params}, `${row.orderNo}.xlsx`)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

onMounted(() => {
  getDeptTree();
});

/**
 * 修改单行总价
 * @param row
 */
function changeTotalPrice(row) {
  row.totalPrice = row.retailPrice * row.quantity
  let s = 0;
  sellOrderDetailList.value.forEach(item => {
    s += item.totalPrice
  });
  form.value.totalPrice = s
}

/**
 * 修改定金计算尾款
 */
function  changeActuallyPaid(){
  //如果定金大于订单金额则等于订单金额
  if (form.value.actuallyPaid>form.value.transactionPrice){
    form.value.actuallyPaid = form.value.transactionPrice
  }
  form.value.finalPayment = form.value.transactionPrice - form.value.actuallyPaid
}

/**
 * 修改成交价计算尾款
 */
function  changeTransactionPrice(){
  //如果定金大于订单金额则等于订单金额
  form.value.finalPayment = form.value.transactionPrice - form.value.actuallyPaid
}

getList();
</script>
